<template>
  <Dividetb>
    <template #top>
      <TopBox :title="'我的模板库'">
        <FilterSearch
          ref="filterSearchRef"
          :placeholder="'请输入文件夹名称'"
          :searchCallBack="searchCallBack"
        />
        <!-- <topButtonGroup :buttonList="tbuttonList" /> -->
        <topButtonGroupDoc :buttonList="tbuttonList" />
      </TopBox>
      <NewFolder
        v-if="newVisible"
        :visible="newVisible"
        @close="closeNewFolder"
        @cancel="cancelNewFolder"
      />
    </template>
    <template #bottom>
      <div class="tableBox" v-if="viewCon">
        <el-table
          size="large"
          class="listTable"
          :data="tableData"
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          align="center"
          height="80vh"
          table-layout="auto"
          v-loading="isLoading"
          @cell-mouse-enter="cellMouseEnter"
          @cell-mouse-leave="cellMouseLeave"
          @selection-change="handleSelectionChange"
          @row-click="currentRowChange"
          @row-dblclick="openFolder"
          ref="tableRef"
          @scroll="handleScroll"
        >
          <el-table-column
            width="30"
            class-name="zhiding"
            label-class-name="zhiding"
          >
            <template #default="scope">
              <el-icon v-if="scope.row.isTop == '1'">
                <svg
                  t="1740105554250"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="888"
                  width="200"
                  height="200"
                >
                  <path
                    d="M572.72420125 170.92152889l388.03137422 346.41455786c20.47053369 23.81432605 24.9561088 56.32018205 11.89551218 84.8531001-13.04894578 28.54456889-40.69639965 46.19559822-72.04882205 46.19559822H758.29885155v241.75502222C758.29885155 957.81956267 703.13210311 1012.98631111 635.42904605 1012.98631111h-245.71630934c-67.69140622 0-122.85815467-55.1550976-122.85815466-122.85815466V648.39643591H124.53951715c-31.3524224 0-58.99987627-17.67433102-72.04882204-46.20724906-13.04894578-28.54456889-8.57502151-61.05042489 11.89551218-84.8531001l388.03137422-346.41455786a79.30729813 79.30729813 0 0 1 60.15330987-27.64745387c23.16187875 0 45.05381547 10.11293298 60.15330987 27.64745387zM348.76001849 566.47934862v323.66045867a41.06922667 41.06922667 0 0 0 40.95271822 40.94106738h245.71630934a41.06922667 41.06922667 0 0 0 40.95271822-40.95271822V566.47934862h218.59314346L512.57089138 226.58926365 130.16687502 566.47934862H348.77166933zM949.87368675 92.91912533H75.268096A40.90611485 40.90611485 0 0 1 34.31537778 51.96640711 40.90611485 40.90611485 0 0 1 75.268096 11.01368889h874.60559075a40.90611485 40.90611485 0 0 1 40.95271823 40.95271822 40.90611485 40.90611485 0 0 1-40.95271823 40.95271822z"
                    p-id="889"
                  ></path>
                </svg>
              </el-icon>
              <!-- {{ scope.row.isTop }} -->
            </template>
          </el-table-column>
          <el-table-column type="selection" width="55" size="large" />
          <el-table-column
            label="序号"
            type="index"
            width="60"
            :index="(index) => index + 1"
          />
          <el-table-column prop="folderName" width="250" show-overflow-tooltip>
            <template #header>
              <div style="width: 100%; text-align: left">文件夹名称</div>
            </template>
            <template #default="scope">
              <div
                style="display: flex; align-items: center"
                class="folderName"
              >
                <el-icon>
                  <folder />
                </el-icon>
                <!-- <span style="margin-left: 10px">
                  {{ scope.row.folderName }}
                </span> -->
                <span
                  style="margin-left: 10px"
                  v-html="scope.row.folderName"
                  class="ellipse"
                >
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="文档数量" width="60" show-overflow-tooltip>
            <template #default="{ row }">
              <div v-html="row.personageTemplateDocumentNumString" class="ellipse"></div>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间">
            <template #default="{ row }">
              <span>{{ getDayOfWeek(row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注"/>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-dropdown placement="bottom" popper-class="opeDropdown">
                <el-button
                  link
                  size="small"
                  :icon="More"
                  class="moreBtn"
                  @click.stop="(e) => e.preventDefault()"
                >
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="item in opebuttonList"
                      :key="item.label"
                      @click="item.onClick(scope.row)"
                    >
                      <el-button
                        link
                        :icon="item.icon"
                        :type="
                          item.label == '置顶' && scope.row.isTop == '1'
                            ? 'warning'
                            : item.type
                        "

                      >
                        <template
                          v-if="item.label == '置顶' && scope.row.isTop == '1'"
                          >取消</template
                        >{{ item.label }}
                      </el-button>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
          <template #append>
            <div class="load-tip">
              <span v-if="tableLoading">加载中...</span>
              <span v-else-if="!hasMore&&tableData.length>0">没有更多数据了</span>
            </div>
          </template>
        </el-table>
      </div>
      <div class="listBox" v-if="!viewCon">
        <div
          v-for="item in tableData"
          :key="item.folderName"
          @contextmenu="showMenu(item, $event)"
          @dblclick="openFolder(item)"
        >
          <div class="listItem flex-center">
            <img src="@/assets/images/folder.png" alt="" />
            <p class="folderName">{{ item.folderName }}</p>
          </div>
        </div>
      </div>
      <div id="tabinput" style="visibility: none; height: 0; overflow: hidden">
        <input type="text" ref="tabinput" />
      </div>
      <WorkFlow1
        v-if="workFlowVisible"
        :visible="workFlowVisible"
        :row="curdata"
        @close="workFlowVisible = false"
        @callback="ChangeWorkFlow"
      />

    </template>
  </Dividetb>
</template>
<script setup>
import { ref, toRaw, onMounted, h, render, nextTick } from "vue";
import { debounce } from "lodash-es";
import {
  More,
  FolderOpened,
  Top,
  EditPen,
  Delete,
} from "@element-plus/icons-vue";
import { ElButton, ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import NewWindow from "@/assets/customIcon/NewWindow.vue";
import WorkFlowIcon from "@/assets/customIcon/WorkFlow.vue";
import MemberAssignmentIcon from "@/assets/customIcon/MemberAssignment.vue";
import useTagStore from "@/stores/tagList";
import Dividetb from "@/layout/components/dividetb.vue";
import TopBox from "@/components/TopTitleBox/index.vue";
import FilterSearch from "@/components/TopTitleBox/FilterSearch.vue";
import topButtonGroup from "@/components/ButtonGroup/topButtonGroup.vue";
import topButtonGroupDoc from "@/components/ButtonGroup/topButtonGroupDoc.vue";
import WorkFlow from "../components/WorkFlow.vue";
import WorkFlow1 from "../components/WorkFlow1.vue";
import NewFolder from "../components/NewFolder.vue";
import { cellMouseEnter, cellMouseLeave } from "@/utils/cellmouseEvent.js";
import { mouseOverEvent, mouseOutEvent } from "@/utils/event.js";
import { getDayOfWeek } from "@/utils/timeChange.js";
import { loading } from "@/utils/topButton.js";

import {
  getKnowledgeList,
  getMyKnowledgeList,
  getKnowledgeInfo,
  renameKnowledge,
  topKnowledge,
  deleteKnowledge,
} from "@/api/folder";
import {
  getMyTemplateList,
  getPersonageTemplateFolder,
  getTemplateInfo,
  addPersonalTemplateFolder,
  updatePersonalTemplateFolder,
  topPersonalTemplateFolder,
  deleteTemplate,
} from "@/api/template.js";
defineOptions({ name: "MyTemplate" });
import router from "@/router";
const tabinput = ref(null);
const route = useRoute();
const tagStore = useTagStore();
const viewCon = ref(true);
const newVisible = ref(false);

const total = ref(0);
const pagination = reactive({
  pageNum: 1,
  pageSize: 20,
});
const filtrateFormData = reactive({
  delFlag: "0",
});
const isLoading = ref(false);
const tableData = ref([]);
const tableLoading = ref(false);
const hasMore = ref(true);

// 滚动事件处理（带防抖）
const handleScroll = debounce((e) => {
  console.log("滚动事件触发", e);
  // 距离底部 300px 时触发
  const bottomThreshold = 300;
  const container = document.querySelector(".listTable .el-scrollbar");
  const parent = document.querySelector(".listTable tbody");
  console.log(container, parent);
  const conRect = container.getBoundingClientRect();
  const parentRect = parent.getBoundingClientRect();
  console.log(conRect, parentRect);
  if (parentRect.bottom - conRect.bottom <= bottomThreshold) {
    console.log("到底了");
    loadMore();
  }
}, 100);

const loadMore = () => {
  if (!hasMore.value || tableLoading.value) return;
  // 获取下一页列表数据
  getMyKnowledgesList();
};
// 按钮列表
const tbuttonList = ref([
  {
    label: "回退",
    icon: "el-icon-back",
    type: "b2",
    onClick: () => {
      console.log("点击了回退");
      tagStore.historyBack({
        name: route.fullPath,
        breadcrumbName: route.query.name || "文档",
      });
    },
  },
  {
    label: "前进",
    icon: "el-icon-right",
    type: "b2",
    onClick: () => {
      console.log("点击了我的文件夹");
      tagStore.historyFoward({
        name: route.fullPath,
        breadcrumbName: "文档",
      });
    },
  },
  // {
  //   label: "添加",
  //   icon: "el-icon-CirclePlus",
  //   type: "b2",
  //   onClick: () => {
  //     console.log("点击了新增文件夹");
  //     // 打开弹窗
  //     newVisible.value = true;
  //   },
  // },
  {
    label: "刷新",
    icon: "el-icon-refresh",
    type: "b2",
    onClick: (e) => {
      // 滚动条的位置不会改变，于是相当于刷新当前位置的数据
      console.log("点击了刷新");
      // 清空搜索条件
      delete filtrateFormData.params;
      filterSearchRef.value.reset();

      loading(e, () => {
        return new Promise((resolve) => {
          // 清空表格数据
          // tableData.value = [];
          isLoading.value = true;
          // 重新获取列表数据
          regainData().then(() => {
            isLoading.value = false;
            ElMessage.success("刷新成功");
            resolve();
          });
        });
      });
    },
  },
  {
    label: "评论",
    icon: "el-icon-ChatDotRound",
    type: "b2",
    onClick: () => {
      console.log("点击了评论");
      // 评论对象是？文档？段落？
    },
  },
  {
    label: "审批",
    icon: "el-icon-stamp",
    type: "b2",
    onClick: () => {
      console.log("点击了审批");
    },
  },
  {
    label: "批量删除",
    icon: "el-icon-delete",
    type: "b2",
    onClick: () => {
      if (selectedFolderIds.value.length == 0) {
        ElMessage.warning("请选择要删除的文件夹");
        return;
      }
      console.log("点击了批量删除");
      ElMessageBox.confirm("确定要删除这些文件夹吗？", "", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        icon: "WarnTriangleFilled",
        // icon: "warning",
        type: "warning",
      }).then(() => {
        deleteTemplate(selectedFolderIds.value.join(",")).then((res) => {
          console.log(res);
          if (res.code == 200) {
            ElMessage.success("删除成功");
            regainData();
          } else {
            ElMessage.error("删除失败");
          }
        });
      });
    },
  },
  {
    label: "列表视图切换",
    icon: "FaAlignJustify",
    type: "b2",
    onClick: () => {
      console.log("点击了列表视图切换");
      viewCon.value = !viewCon.value;
    },
  },
]);
const opebuttonList = [
  {
    icon: FolderOpened,
    label: "打开",
    onClick: (row) => {
      openFolder(row);
    },
  },
  {
    icon: NewWindow,
    label: "新窗口打开",
    onClick: (row) => {
      openFolderOnNewWindow(row);
    },
  },
  {
    icon: EditPen,
    label: "重命名",
    onClick: (row) => {
      ElMessageBox.prompt("请输入新的文件夹名称", "", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "文件夹名称不能为空",
      })
        .then(({ value }) => {
          console.log("重命名", value);
          // 调用重命名接口
          renameKnowledge({ id: row.id, folderName: value }).then(
            async (res) => {
              if (res.code !== 200) return;
              ElMessage.success("重命名成功!");
              regainData();
            }
          );
        })
        .catch(() => {
          console.log("取消");
        });
    },
  },
  {
    icon: Top,
    label: "置顶",
    onClick: (row) => {
      console.log("成员", row);
      topKnowledge({ id: row.id }).then((res) => {
        if (res.code !== 200) return;
        if (row.isTop == 1) {
          ElMessage.success("取消置顶成功!");
        } else {
          ElMessage.success("置顶操作成功!");
        }
        regainData();
      });
    },
  },
  {
    icon: Delete,
    label: "删除",
    type: "danger",
    onClick: (row) => {
      console.log("删除文件夹", row);
      ElMessageBox.confirm("确定删除该文件夹吗？", "", {}).then(() => {
        deleteTemplate(row.id).then(async (res) => {
          console.log(res);
          if (res.code !== 200) return;
          ElMessage.success("删除文件夹成功!");
          // 删除成功后，重新获取列表数据
          regainData();
        });
      });
    },
  },
];
const filterSearchRef = ref(null);
const searchCallBack = (word, time) => {
  console.log("搜索回调", word, time);
  let params = {};
  if (word) {
    params.searchKey = word;
  }
  if (time) {
    params.startTime = time[0] ? time[0] + " 00:00:00" : null;
    params.endTime = time[1] ? time[1] + " 23:59:59" : null;
  }
  filtrateFormData.params = params;
  regainData();
};
const closeNewFolder = async () => {
  newVisible.value = false;
  hasMore.value = true;
  getMyKnowledgesList();
};
const cancelNewFolder = () => {
  newVisible.value = false;
};
const openFolder = (row) => {
  console.log("打开文件夹", row);
  const folderName = row.folderName;
  // console.log(encodeURIComponent(folderName), "encodeURIComponent");
  router.replace({
    name: "Files",
    query: {
      id: row.id,
      name: folderName,
      pageFrom:"mytemplate",
      modelId: row.modelId||'null',
    },
  });
  tagStore.refreshTagList(
    { name: "/document/l/mytemplate", breadcrumbName: "我的模板库" },
    {
      name: `/document/l/files`,
      breadcrumbName: folderName,
      fullPath: `/document/l/files?id=${row.id}&name=${folderName}&pageFrom=mytemplate&modelId=${row.modelId||'null'}`,
    }
  );
};
const openFolderOnNewWindow = (row) => {
  console.log("在新窗口打开文件夹", row);
  const folderName = row.folderName;
  router.push({
    name: "Files",
    query: {
      id: row.id,
      name: folderName,
      pageFrom:"mytemplate",
      modelId: row.modelId||'null',
    }
  });
  tagStore.addTagList({
    name: `/document/l/files`,
    breadcrumbName: folderName,
    fullPath: `/document/l/files?id=${row.id}&name=${folderName}&pageFrom=mytemplate&modelId=${row.modelId||'null'}`,
    historyList: [
      {
        name: `/document/l/files`,
        breadcrumbName: folderName,
        fullPath: `/document/l/files?id=${row.id}&name=${folderName}&pageFrom=mytemplate&modelId=${row.modelId||'null'}`,
      },
    ],
  });
};
const AddToKnowledge = (row) => {
  let selectedFolderName;
  if (row) {
    selectedFolderName = row.folderName;
  } else {
    selectedFolderName = tableData.value.find(
      (item) => item.id == selectedFolderIds[0]
    ).folderName;
  }
  console.log(selectedFolderName);
  ElMessageBox.confirm(
    `确定要将文件夹${selectedFolderName}添加到知识库吗？`,
    "",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: true,
    }
  ).then(() => {});
};
const curdata = ref({});
// 流程配置
const workFlowVisible = ref(false);
const ChangeWorkFlow = (val) => {
  ElMessage.info("调用接口修改流程配置");
};
// 成员分配
const memberVisible = ref(false);
const showMenu = (row, event) => {
  console.log("显示菜单", row, event);
  event.preventDefault();
  console.log(event.target);
  console.dir(event.target);
  console.log(event.target.closest(".listItem"));
  const listItem = event.target.closest(".listItem");
  // listItem.dispatchEvent(mouseOverEvent);
  listItem.classList.add("hovering");
  console.log(event.clientX, event.clientY);
  curdata.value = row;
  Menu.getInstance({ top: event.clientY, left: event.clientX });
};
const Menu = (function () {
  var menu;
  function Singleton(options) {
    // this.container = document.getElementById('contextMenu')
    this.parent = document.querySelector(".listBox");
    this.container = document.createElement("div");
    this.container.id = "contextMenu";
    createButton.call(this);
    this.container.style.top = options.top + "px";
    this.container.style.left = options.left + "px";
    this.parent.appendChild(this.container);
  }
  function createButton() {
    const y = h(
      "div",
      {
        style: {
          width: "100%",
        },
      },
      opebuttonList.map((cur) =>
        h(
          ElButton,
          {
            type: cur.type,
            icon: cur.icon,
            link: true,
            style: {
              width: "100%",
              padding: "7px",
              marginLeft: "0",
              display: "flex",
              justifyContent: "flex-start",
              alignItems: "center",
            },
            onClick: () => cur.onClick(curdata.value),
          },
          cur.label || "无名按钮"
        )
      )
    );
    console.log(y);
    render(y, this.container);
  }
  function update(options) {
    console.log(this, menu, options);
    menu.container.style.top = options.top + "px";
    menu.container.style.left = options.left + "px";
  }
  return {
    getInstance: function (options) {
      if (!menu) {
        menu = new Singleton(options);
      } else {
        update(options);
      }
      tabinput.value.focus();
      menu.container.style.display = "flex";
      return menu;
    },
    hide: function () {
      menu.container.style.display = "none";
    },
  };
})();
const regainData = () => {
  pagination.pageNum = 1;
  hasMore.value = true;
  return getMyKnowledgesList();
};
// 获取列表数据
const getMyKnowledgesList = async (data = {}) => {
  if (!hasMore.value) return;
  let params = { ...pagination, ...filtrateFormData, ...data };
  console.log(params, "获取列表数据1");
  tableLoading.value = true;
  await getPersonageTemplateFolder({ ...params })
    .then((res) => {
      if (res.code === 200) {
        if (pagination.pageNum == 1) {
          tableData.value = res.rows;
        } else {
          tableData.value = [...tableData.value, ...res.rows];
        }
        total.value = res.total;
        hasMore.value = total.value > tableData.value.length;
        pagination.pageNum++;
      }
    })
    .finally(() => {
      tableLoading.value = false;
    });
};
const tableRef = ref(null);
const selectedFolderIds = ref([]); // 多选框选中数据
const multiple = ref(true); // 是否多选
const once = ref(true); //是否单选
const curFolder = ref("");
// 多选框选中数据
function handleSelectionChange(selection) {
  selectedFolderIds.value = selection.map((item) => item.id);
  multiple.value = !selection.length;
  if (selection.length == 1) {
    once.value = false;
  } else {
    once.value = true;
  }
}
const currentRowChange = (curRow) => {
  console.log(curRow);
  const flag = selectedFolderIds.value.includes(curRow.id);
  tableRef.value.toggleRowSelection(curRow, !flag);
  curFolder.value = curRow.folderName;
};
onMounted(async () => {
  console.log("我的文件夹页面挂载完成");
  tabinput.value.addEventListener("blur", (e) => {
    console.log("失去焦点", e);
    Menu.hide();
    document.querySelector(".listItem.hovering").classList.remove("hovering");
  });
  // 调用接口获取数据
  getMyKnowledgesList();
});
</script>
<style lang="scss" scoped>
.tableBox {
  :deep(.cell) {
    display: flex;
    justify-content: center;
    font-size: var(--el-font-size-base);
    width: 100%;
    white-space: nowrap;
    &:has(.folderName) {
      justify-content: start;
    }
    .folderName {
      width: 100%;
    }
    // span {
    //   overflow: hidden;
    //   text-overflow: ellipsis;
    // }
    .ellipse {
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
  :deep(.zhiding) {
    border-bottom: none !important;
  }
  .moreBtn {
    display: none;
    &.active {
      display: flex;
    }
  }
}
.listBox {
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  gap: 20px;
  .listItem {
    width: 120px;
    padding: 10px;
    // border: 1px solid #e0e0e0;
    border-radius: 2px;
    flex-direction: column;
    &.hovering,
    &:hover {
      border: 1px solid #ccc;
      background-color: #cccccc70;
    }
    img {
      width: 50%;
    }
    .folderName {
      // font-size: 24px;
      width: 98%;
      overflow: hidden;
      text-overflow: ellipsis; // 超出部分显示...
      white-space: nowrap; // 不换行
      text-align: center;
    }
  }
}
.opeDropdown {
  button {
    width: 100%;
    justify-content: start;
  }
}
</style>
<style lang="scss">
#contextMenu {
  position: absolute;
  top: 0;
  left: 0;
  border: 1px solid #ccc;
  box-shadow: 2px 2px 3px #cccccc90;
  background-color: #fff;
  padding: 10px;
  display: none;
}
</style>
